﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace ProjectHT.YKDGVB2012.Core.TimeJob
{
    public class CheckExpires : SPJobDefinition
    {

        SPWeb _sweb;
        string _siteurl;
        public CheckExpires()
            : base()
        {

        }

        public CheckExpires(SPWebApplication spWebApplication)
            : base("CheckExpires", spWebApplication, null, SPJobLockType.Job)
        {
            this.Title = "CheckExpires";

        }

        public override void Execute(Guid targetInstanceId)
        {
            if (!string.IsNullOrEmpty(this.Properties["SiteUrl"].ToString()))
            {
                _siteurl = this.Properties["SiteUrl"].ToString();
            }

            if (!string.IsNullOrEmpty(_siteurl))
            {
                using (var mySite = new SPSite(_siteurl))
                {
                    using (_sweb = mySite.OpenWeb())
                    {
                        _sweb.AllowUnsafeUpdates = true;

                        // open SharePoint List
                        var olist = _sweb.Lists[Common.MainList.MAINLIST];
                        if (olist != null)
                        {
                            //check number item in list 
                            if (olist.ItemCount > 0)
                            {
                                var currentdate = DateTime.Today;
                                var listitem = olist.Items.Cast<SPListItem>().ToList();

                                if (listitem.Where(p => Convert.ToDateTime(p["Created"]) >= currentdate).Count() > 0)
                                {
                                    //change trang thai Item

                                    foreach (SPListItem item in listitem.Where(p => Convert.ToDateTime(p["Created"]) >= currentdate))
                                    {
                                        item[Common.MainList.FIELDEXPIRE] = true;
                                        item[Common.MainList.FIELDEXPIREDATE] = currentdate;
                                        item.Update();
                                    }
                                }
                            }
                        }
                        _sweb.AllowUnsafeUpdates = false;
                    }
                }
            }


        }


    }
}
